package com.zqweb.gulimall.essearch.controller;

import com.zqweb.common.es.SkuESModel;
import com.zqweb.common.exception.ExpCodeAndMsgEnum;
import com.zqweb.common.utils.R;
import com.zqweb.gulimall.essearch.service.EsSaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/es/save")
public class EsSaveController {
    @Autowired
    private EsSaveService esSaveService;

    // 保存商品ES模型数据到ES服务器
    @PostMapping("/product")
    public R saveESModel(@RequestBody List<SkuESModel> skuESModels){
        System.out.println("================== 进入ES的Model上传服务！ ===================");
        boolean status = false;// 商品上架状态
        try {
            // 注意：saveESModel方法返回的是ES存储数据发生错误时对应的为true
            status = esSaveService.saveESModel(skuESModels);
        } catch (IOException e) {
            // 这里是由于网络不通等原因，未将数据传输到ES服务器，发生了异常
            log.error("ES模型数据存储失败，原因为：{}",e.getMessage());
            return R.error(ExpCodeAndMsgEnum.PRODUCTUP_EXCEPTION.getCode(),ExpCodeAndMsgEnum.PRODUCTUP_EXCEPTION.getMsg());
        }
        // 这里判断的是数据传输到了ES服务器，对于数据的存储发生了异常
        if(!status) return R.ok();
        else return R.error(ExpCodeAndMsgEnum.PRODUCTUP_EXCEPTION.getCode(),ExpCodeAndMsgEnum.PRODUCTUP_EXCEPTION.getMsg());
    }
}
